package com.mulong.mall.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.mulong.mall.constants.Constants;
import com.mulong.mall.domain.bo.distributor.*;
import com.mulong.mall.domain.param.distributor.*;
import com.mulong.mall.domain.result.distributor.*;
import com.mulong.mall.service.DistributorDataDownloadService;
import com.mulong.mall.service.support.DistributorDataDownloadSupport;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.mulong.common.dao.mall.ChannelDao;
import com.mulong.common.dao.mall.InventoryDao;
import com.mulong.common.domain.pojo.mall.SupplierChannel;
import com.mulong.common.domain.pojo.mall.custom.InventoryChannelQuery;
import com.mulong.common.domain.pojo.mall.custom.DownloadInventory;
import com.mulong.common.domain.pojo.mall.custom.DownloadInventoryQuery;
import com.mulong.common.exception.ErrorEnums;
import com.mulong.common.exception.MulongException;
import com.mulong.common.util.MulongUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * DataDownloadServiceImpl
 * 
 * @author mulong
 * @data 2021-05-29 21:21:50
 */
@Slf4j
@Service
public class DistributorDataDownloadServiceImpl implements DistributorDataDownloadService {
    @Autowired
    private ChannelDao channelDao;
    @Autowired
    private InventoryDao inventoryDao;
    @Autowired
    private DistributorDataDownloadSupport distributorDataDownloadSupport;

    /**
     * 库存渠道列表
     * 
     * @author mulong
     */
    @Override
    public GetDataDownloadInventoryChannelByPageResult getInventoryChannelByPage(GetDataDownloadInventoryChannelByPageParam param) {
        InventoryChannelQuery inventoryChannelQuery = new InventoryChannelQuery();
        inventoryChannelQuery.setSupplierChannelId(param.getSupplierChannelId());
        inventoryChannelQuery.setOrderBy("`inventory_update_time` DESC");
        int pageNo = param.getPageNo() == null ? Constants.DEFAULT_PAGE_NO : param.getPageNo();
        int pageSize = param.getPageSize() == null ? Constants.DEFAULT_PAGE_SIZE : param.getPageSize();
        PageHelper.startPage(pageNo, pageSize, true);
        Page<SupplierChannel> page = (Page<SupplierChannel>) channelDao.queryInventoryChannel(inventoryChannelQuery);
        GetDataDownloadInventoryChannelByPageResult getDataDownloadInventoryChannelByPageResult = new GetDataDownloadInventoryChannelByPageResult(page.getPageNum(), page.getPageSize(), (int)page.getTotal());
        List<SupplierChannel> list = page.getResult();
        if (!CollectionUtils.isEmpty(list)) {
            getDataDownloadInventoryChannelByPageResult.setResult(list.stream().map(DataDownloadInventoryChannel::new).collect(Collectors.toList()));
        }
        return getDataDownloadInventoryChannelByPageResult;
    }

    /**
     * 库存下载
     * 
     * @author mulong
     */
    @Override
    public ResponseEntity<byte[]> downloadInventory(DownloadDataDownloadInventoryParam param) {
        Integer supplierChannelId = param.getSupplierChannelId();
        if (supplierChannelId == null) {
            throw new MulongException(ErrorEnums.ILLEGAL_LESS_PARAM_TEMPLETE.format("supplierChannelId"));
        }
        String fileName = "库存.xls";
        // get data
        DownloadInventoryQuery downloadInventoryQuery = new DownloadInventoryQuery();
        downloadInventoryQuery.setSupplierChannelId(supplierChannelId);
        downloadInventoryQuery.setOrderBy("i.`sku` ASC");
        List<DownloadInventory> productInventoryRecords = inventoryDao.queryDownloadInventory(downloadInventoryQuery);
        // build content
        byte[] content = null;
        try (HSSFWorkbook workbook = new HSSFWorkbook()) {
            HSSFSheet sheet = workbook.createSheet(Constants.DISTRIBUTOR_DOWNLOAD_INVENTORY_SHEET_NAME);            
            List<String> titles = Constants.DISTRIBUTOR_DOWNLOAD_INVENTORY_SHEET_TITLE;
            MulongUtil.addTitle(workbook, sheet, titles);
            HSSFCellStyle defaultStyle = MulongUtil.getDefaultCellStyle(workbook);
            int lastRowNum = sheet.getLastRowNum();
            for (int j = 0; j < productInventoryRecords.size(); j++) {
                DownloadInventory productInventoryRecord = productInventoryRecords.get(j);
                HSSFRow row = sheet.createRow(j + (lastRowNum + 1));
                distributorDataDownloadSupport.addRow(row, productInventoryRecord, defaultStyle);
            }
            content = MulongUtil.toByteArray(workbook);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            content = null;
        }
        if (content == null) {
            throw new MulongException(ErrorEnums.HANDLE_FAILED_TEMPLETE.format("导出数据异常"));
        }
        // build response
        return MulongUtil.buildDownloadResponse("application/octet-stream", fileName, content);
    }

    /**
     * 新增款式推荐包列表
     * 
     * @author mulong
     */
    @Override
    public GetDataDownloadRecommendationByPageResult getRecommendationByPage(
            GetDataDownloadRecommendationByPageParam param) {
        // TODO Auto-generated method stub
        GetDataDownloadRecommendationByPageResult getDataDownloadRecommendationByPageResult = new GetDataDownloadRecommendationByPageResult(0, 0, 0);
        return getDataDownloadRecommendationByPageResult;
    }

    /**
     * 新增款式推荐包下载
     * 
     * @author mulong
     */
    @Override
    public ResponseEntity<byte[]> downloadRecommendation(DownloadDataDownloadRecommendationParam param) {
        String fileName = "";
        // get data
        // TODO
        // build content
        byte[] content = null;
        try (HSSFWorkbook workbook = new HSSFWorkbook()) {
            // TODO            
            content = MulongUtil.toByteArray(workbook);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            content = null;
        }
        if (content == null) {
            throw new MulongException(ErrorEnums.HANDLE_FAILED_TEMPLETE.format("导出数据异常"));
        }
        // build response
        return MulongUtil.buildDownloadResponse("application/octet-stream", fileName, content);
    }

    /**
     * 数据包列表
     * 
     * @author mulong
     */
    @Override
    public GetDataDownloadDataPackageByPageResult getDataPackageByPage(GetDataDownloadDataPackageByPageParam param) {
        // TODO Auto-generated method stub
        GetDataDownloadDataPackageByPageResult getDataDownloadDataPackageByPageResult = new GetDataDownloadDataPackageByPageResult(0, 0, 0);
        return getDataDownloadDataPackageByPageResult;
    }

    /**
     * 数据包下载
     * 
     * @author mulong
     */
    @Override
    public ResponseEntity<byte[]> downloadDataPackage(DownloadDataDownloadDataPackageParam param) {
        String fileName = "";
        // get data
        // TODO
        // build content
        byte[] content = null;
        try (HSSFWorkbook workbook = new HSSFWorkbook()) {
            // TODO            
            content = MulongUtil.toByteArray(workbook);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            content = null;
        }
        if (content == null) {
            throw new MulongException(ErrorEnums.HANDLE_FAILED_TEMPLETE.format("导出数据异常"));
        }
        // build response
        return MulongUtil.buildDownloadResponse("application/octet-stream", fileName, content);
    }

    /**
     * 商品数据列表
     * 
     * @author mulong
     */
    @Override
    public GetDataDownloadGoodsByPageResult getGoodsByPage(GetDataDownloadGoodsByPageParam param) {
        // TODO Auto-generated method stub
        GetDataDownloadGoodsByPageResult getDataDownloadGoodsByPageResult = new GetDataDownloadGoodsByPageResult(0, 0, 0);
        return getDataDownloadGoodsByPageResult;
    }

    /**
     * 商品数据下载
     * 
     * @author mulong
     */
    @Override
    public ResponseEntity<byte[]> downloadGoods(DownloadDataDownloadGoodsParam param) {
        String fileName = "";
        // get data
        // TODO
        // build content
        byte[] content = null;
        try (HSSFWorkbook workbook = new HSSFWorkbook()) {
            // TODO            
            content = MulongUtil.toByteArray(workbook);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            content = null;
        }
        if (content == null) {
            throw new MulongException(ErrorEnums.HANDLE_FAILED_TEMPLETE.format("导出数据异常"));
        }
        // build response
        return MulongUtil.buildDownloadResponse("application/octet-stream", fileName, content);
    }

}
